<template>
  <div ref="editor" class="editor-wrapper"></div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, watch } from 'vue'
import { EditorView, basicSetup } from 'codemirror'
import { markdown } from '@codemirror/lang-markdown'
import { oneDark } from '@codemirror/theme-one-dark'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])
const editor = ref(null)
let editorView = null

const createEditor = () => {
  if (!editor.value) return

  editorView = new EditorView({
    doc: props.modelValue,
    extensions: [
      basicSetup,
      markdown(),
      oneDark,
      EditorView.updateListener.of((update) => {
        if (update.docChanged) {
          emit('update:modelValue', update.state.doc.toString())
        }
      })
    ],
    parent: editor.value
  })
}

watch(() => props.modelValue, (newValue) => {
  if (editorView && editorView.state.doc.toString() !== newValue) {
    editorView.dispatch({
      changes: {
        from: 0,
        to: editorView.state.doc.length,
        insert: newValue
      }
    })
  }
})

onMounted(() => {
  createEditor()
})
</script>

<style scoped>


.editor-wrapper {
  width: 100%;
  height: 100vh;
  border: 1px solid #ddd;
  border-radius: 4px;
  position: relative;
  background-color: #282c34;
  overflow: auto;
}

.editor-wrapper :deep(.cm-editor) {
  height: 100%;
  min-height: 500px;
}

.editor-wrapper :deep(.cm-editor.cm-focused) {
  outline: none;
  border-color: #42b883;
  box-shadow: 0 0 0 2px rgba(66, 184, 131, 0.2);
}

.editor-wrapper :deep(.cm-scroller) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  line-height: 1.6;
  font-size: 14px;
}
</style>
